<template>
  <canvas 
    ref="canvasEl"
    :width="width"
    :height="height"
    @mousedown="startDrawing"
    @mousemove="draw"
    @mouseup="stopDrawing"
    @mouseleave="stopDrawing"
    @touchstart="startDrawing"
    @touchmove="draw"
    @touchend="stopDrawing"
  ></canvas>
</template>

<script>
export default {
  name: 'SquareCanvas',
  props: {
    width: {
      type: Number,
      default: 400
    },
    height: {
      type: Number,
      default: 400
    }
  },
  emits: ['draw'],
  data() {
    return {
      isDrawing: false,
      lastX: 0,
      lastY: 0,
      ctx: null
    }
  },
  mounted() {
    this.initCanvas();
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.canvasEl;
      this.ctx = canvas.getContext('2d');
      this.clear();
    },
    
    startDrawing(e) {
      this.isDrawing = true;
      const pos = this.getPosition(e);
      this.lastX = pos.x;
      this.lastY = pos.y;
    },
    
    draw(e) {
      if (!this.isDrawing) return;
      
      const pos = this.getPosition(e);
      this.ctx.beginPath();
      this.ctx.moveTo(this.lastX, this.lastY);
      this.ctx.lineTo(pos.x, pos.y);
      this.ctx.strokeStyle = '#000000';
      this.ctx.lineWidth = 20;
      this.ctx.lineCap = 'round';
      this.ctx.lineJoin = 'round';
      this.ctx.stroke();
      
      // 发射绘制事件数据
      this.$emit('draw', {
        from: { x: this.lastX, y: this.lastY },
        to: { x: pos.x, y: pos.y }
      });
      
      this.lastX = pos.x;
      this.lastY = pos.y;
    },
    
    stopDrawing() {
      this.isDrawing = false;
    },
    
    getPosition(e) {
      const canvas = this.$refs.canvasEl;
      const rect = canvas.getBoundingClientRect();
      
      let clientX, clientY;
      if (e.type.includes('touch')) {
        clientX = e.touches[0].clientX;
        clientY = e.touches[0].clientY;
      } else {
        clientX = e.clientX;
        clientY = e.clientY;
      }
      
      return {
        x: clientX - rect.left,
        y: clientY - rect.top
      };
    },
    
    clear() {
      this.ctx.fillStyle = '#ffffff';
      this.ctx.fillRect(0, 0, this.width, this.height);
      this.ctx.fillStyle = '#000000';
    }
  }
}
</script>

<style scoped>
canvas {
  display: block;
  background-color: white;
  cursor: crosshair;
  touch-action: none;
}
</style>